package brs;

import brs.http.common.Parameters;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


//预挖功能
public class PreMine {
    public static class PreMineUser {
        public String secret;
        public String amount;
        public String id;
        public int height;
    }
    public static class PreMineJson {
        public String totalSupply;
        public PreMineUser[] preMineUsers;
    }
    public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException {
        File premineFile = new File("premine.json");

        if (premineFile == null) {
            System.out.println("failed to find premine.json");
            return ;
        }
        String mainPath = Paths.get(premineFile.toURI()).toString();
        String data = new String(Files.readAllBytes(Paths.get(mainPath)));
        Gson gson = new Gson();
        PreMineJson premine = gson.fromJson(data, PreMineJson.class);

        //查询区块高度，如果高度已经超过预挖高度，则忽略
        JsonObject response = retrieve("getMiningInfo",Arrays.asList());
        int height = response.get("height").getAsInt();


        for (PreMineUser user :premine.preMineUsers) {
            response = retrieve("submitNonce",Arrays.asList(
                    new BasicNameValuePair(Parameters.SECRET_PHRASE_PARAMETER, user.secret),
                    new BasicNameValuePair(Parameters.NONCE_PARAMETER, "1234"),
                    new BasicNameValuePair(Parameters.ACCOUNT_ID_PARAMETER, user.id),
                    new BasicNameValuePair(Parameters.BLOCK_HEIGHT_PARAMETER, String.valueOf(user.height))
            ));

            if (response.get("result").getAsString().equals("success")) {
                System.out.println("premine block at height [" + user.height + "] done.");
            } else {
                System.out.println("failed to premine, response: " +response.toString());
                return;
            }

            //等待区块生成后再继续下一个区块
            Thread.sleep(15000);
        }

        System.out.println("premine done!");
    }

    public static JsonObject retrieve(String requestType, List<BasicNameValuePair> extraParams) throws IOException {
        HttpClient httpclient = HttpClientBuilder.create().build();
        final JsonParser parser = new JsonParser();
        final HttpPost post = new HttpPost("/burst");

        final List<NameValuePair> urlParameters = new ArrayList<>();
        urlParameters.add(new BasicNameValuePair("requestType", requestType));
        urlParameters.add(new BasicNameValuePair("random", "0.7113466594385798"));
        urlParameters.addAll(extraParams);

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        final HttpResponse result = httpclient.execute(new HttpHost("120.76.247.6", 8125), post);

        return (JsonObject) parser.parse(EntityUtils.toString(result.getEntity(), "UTF-8"));
    }
}
